package utils

import (
	"errors"
	"time"

	"github.com/golang-jwt/jwt/v5"
)

type jwtUserKey struct{}

var JwtUserKey = jwtUserKey{}

const JwtExpiredAt = 24 * 60 * 60 * 10 // 10天

type JwtUser struct {
	Id       uint   `json:"id"`
	Username string `json:"username"`
	Email    string `json:"email"`
	Mobile   string `json:"mobile"`
}

type JwtClaims struct {
	User JwtUser
	jwt.RegisteredClaims
}

func GetJwtToken(secretKey string, user JwtUser) (string, error) {
	claims := JwtClaims{
		User: user,
		RegisteredClaims: jwt.RegisteredClaims{
			ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Duration(JwtExpiredAt) * time.Second)),
			IssuedAt:  jwt.NewNumericDate(time.Now()),
			NotBefore: jwt.NewNumericDate(time.Now()),
		},
	}
	return jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString([]byte(secretKey))
}

func ParseTokenHs256(token_string string, sign_key string) (*JwtUser, error) {
	token, err := jwt.ParseWithClaims(token_string, &JwtClaims{}, func(token *jwt.Token) (any, error) {
		return []byte(sign_key), nil //返回签名密钥
	})
	if err != nil {
		return nil, err
	}
	if claims, ok := token.Claims.(*JwtClaims); ok && token.Valid {
		return &claims.User, nil
	} else {
		return nil, errors.New("token invalid")
	}
}
